//
//  BIBluetoothModel.m
//  BIBluetoothModule
//
//  Created by Yown on 2024/1/21.
//

#import "BIBluetoothModel.h"

@implementation BIBluetoothModel

- (instancetype)init {
    self = [super init];
    if (self) {
        self.state = kBIBluetoothDisconnected;
    }
    return self;
}

- (void)disconnectBluetooth {
    self.state = kBIBluetoothDisconnected;
    self.deviceModel = nil;
    self.writeCharacteristic = nil;
    self.readCharacteristic = nil;
    self.selectTimeInterval = 0;
}

- (void)setState:(BIBluetoothState)state {
    _state = state;
    if (state == kBIBluetoothConnected) {
        self.selectTimeInterval = [[NSDate date] timeIntervalSince1970];
    } else if (state == kBIBluetoothDisconnected) {
        self.selectTimeInterval = 0;
    }
}

- (NSString *)macAddress {
    // 如果大于等于17位，且包含有冒号，那就是一个蓝牙外设正常的mac地址
    // 如果大于等于12位，且不包含冒号，则取前12位，添加冒号就是外设正常的mac地址
    if (self.manufacturer.length >= 17 && [self.manufacturer containsString:@":"]) {
        return [self.manufacturer substringToIndex:17];
    } else if (self.manufacturer.length >= 12 && ![self.manufacturer containsString:@":"]) {
        NSString *result = [self.manufacturer substringToIndex:12];
        NSMutableString *mstring = [NSMutableString stringWithString:result];
        [mstring insertString:@":" atIndex:2];
        [mstring insertString:@":" atIndex:5];
        [mstring insertString:@":" atIndex:8];
        [mstring insertString:@":" atIndex:11];
        [mstring insertString:@":" atIndex:14];
        return mstring;
    } else {
        return self.manufacturer;
    }
}

@end
